package leetcode.editor.cn;

public class Solution1373 {

    int maxSum = 0;

    public int maxSumBST(TreeNode root) {
        helper(root);
        return maxSum;
    }

    int[] helper(TreeNode root){
        if (root == null) return new int[]{1, Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
        int[] left = helper(root.left);
        int[] right = helper(root.right);
        int[] res = new int[4];
        // 这个 if 在判断以 root 为根的二叉树是不是 BST
        if (left[0]==1 && right[0]==1 && root.val>left[2] && root.val<right[1]){
            res[0] = 1;
            // 判断BST的最小值
            res[1] = Math.min(left[1], root.val);
            // 判断BST的最大值
            res[2] = Math.max(right[2], root.val);
            // 计算该树的总数
            res[3] = left[3] + right[3] + root.val;
            maxSum = Math.max(maxSum, res[3]);
        }else {
            // 不是BST
            res[0] = 0;
        }
        return res;
    }
}
